package work3_6;

public class MyDBLink {
    //链首
    private Node first;
    //链尾
    private Node last;
    //大小
    private int size;
    //添加方法
    public void add(Object element){
        if(last==null) {
            //没有元素
            Node node = new Node(null, element, null);
            first = node;
            last = node;
        }else{
            Node node=new Node(last,element,null);
            last.next=node;
            last=node;
        }
        size++;
    }
    /**
     *  根据下标删除元素
     */
    public Object remove(int index){
        //TODO(index合法性)
        Node node=getNode(index);
        remove(node);
        return node.value;
    }
    /**
     * 删除指定元素
     */
    public boolean remove(Object element){
        //TODO(index的合法性)
        Node node=first;
        for (int i = 0; i < size; i++) {
            if(node.value.equals(element)){
                break;
            }else{
                node=node.next;
            }
        }
        remove(node);
        return true;
    }
    /**
     * 在链表删除某个结点
     */
    private void remove(Node node){
        if(first==last){
            first=null;
            last=null;
        }
        if(node==first){
            first.next.pre=null;
            first=first.next;
        } else if (node==last) {
            last.pre.next=null;
            last=last.pre;
        }else{
            node.pre.next=node.next;
            node.next.pre=node.pre;
        }
        node.pre=null;
        node.next=null;
    }
    /**
     * 根据下标找Node结点
     */
    private Node getNode(int index){
        //TODO(index合法性)
        Node node;
        if(index<size/2){
            node=first;
            for (int i = 0; i < index; i++) {
                node=node.next;
            }
        }else{
            node=last;
            for (int i = 0; i < size-index; i++) {
                node=node.pre;
            }
        }
        return node;
    }
    public Object get(int index){
        return getNode(index).value;
    }
    public int size(){
        return this.size;
    }
    public String toString(){
        StringBuilder sb=new StringBuilder("MyDBLink[");
        Node node=first;
        while(node!=null){
            sb.append(node.value+",");
            node=node.next;
        }
        return sb.substring(0,sb.length()-2)+"]";
    }
    public class Node{
        private Object value;
        private Node pre;
        private Node next;
        public Node(Node pre,Object value,Node next){
            this.pre=pre;
            this.value=value;
            this.next=next;
        }
    }
}


